package com.xxxx.seckill.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxxx.seckill.mapper.OrderMapper;
import com.xxxx.seckill.mapper.SeckillOrderMapper;
import com.xxxx.seckill.pojo.Order;
import com.xxxx.seckill.pojo.SeckillGoods;
import com.xxxx.seckill.pojo.SeckillOrder;
import com.xxxx.seckill.pojo.User;
import com.xxxx.seckill.service.IOrderService;
import com.xxxx.seckill.service.ISeckillGoodsService;
import com.xxxx.seckill.service.ISeckillOrderService;
import com.xxxx.seckill.vo.GoodsVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;


/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wyd
 */
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

    @Autowired
    private ISeckillGoodsService seckillGoodsService;
    @Autowired
    private ISeckillOrderService seckillOrderService;
    @Autowired
    private OrderMapper orderMapper;

    /**
     * 生成秒杀订单
     * @param user
     * @param goods
     * @return
     */
    @Override
    public Order seckillOrder(User user, GoodsVo goods) {

        //秒杀商品
        LambdaQueryWrapper<SeckillGoods> wrapper = new LambdaQueryWrapper<>();

        wrapper.eq(SeckillGoods::getGoodsId,goods.getId());

        //根据商品ID查询的秒杀商品
        SeckillGoods seckillGoods = seckillGoodsService.getOne(wrapper);
        //秒杀商品减库存
        seckillGoods.setStockCount(seckillGoods.getStockCount() - 1);
        //更新秒杀商品信息
        seckillGoodsService.updateById(seckillGoods);

        //生成订单信息
        Order order = new Order();

        order.setCreateDate(new Date());
        order.setUserId(user.getId());
        order.setDeliverAddrId(0L);
        order.setGoodsCount(1);
        order.setStatus(0);
        order.setOrderChannel(1);
        order.setGoodsName(goods.getGoodsName());
        //秒杀价格
        order.setGoodsPrice(seckillGoods.getSeckillPrice());
        order.setGoodsId(goods.getId());

        //保存订单信息
        int insertResult = orderMapper.insert(order);

        if (insertResult < 1){

            System.out.println("order数据插入失败！");
        }

        //生成秒杀订单
        SeckillOrder seckillOrder = new SeckillOrder();

        seckillOrder.setUserId(user.getId());
        seckillOrder.setOrderId(order.getId());
        seckillOrder.setGoodsId(goods.getId());

        //保存秒杀订单信息
        seckillOrderService.save(seckillOrder);

        return order;
    }
}
